package com.springboot3login.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot3login.dao.UserMapper;
import com.springboot3login.domain.Result;
import com.springboot3login.domain.ResultEnum;
import com.springboot3login.domain.dto.UserLoginDTO;
import com.springboot3login.domain.entity.User;
import com.springboot3login.domain.vo.UserLoginVO;
import com.springboot3login.exception.AccountForbiddenException;
import com.springboot3login.exception.AccountNotFoundException;
import com.springboot3login.exception.CaptchaErrorException;
import com.springboot3login.exception.PasswordErrorException;
import com.springboot3login.service.UserService;
import com.springboot3login.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Map;

/**
* @author admin
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2024-02-26 14:18:08
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Resource
    private  UserMapper userMapper;

    @Resource
    private  StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<UserLoginVO> login(UserLoginDTO userLoginDTO) {
        // 获取验证码id
        String captchaId = userLoginDTO.getCaptchaId();
        // 获取用户提交验证码
        String userCaptcha = userLoginDTO.getCaptcha();
        // 获取缓存验证码
        String cacheCaptcha = stringRedisTemplate.opsForValue().get("captcha:" + captchaId);
        // 比较验证码是否正确
        if (cacheCaptcha == null || !cacheCaptcha.equalsIgnoreCase(userCaptcha)) {
            throw new CaptchaErrorException(ResultEnum.USER_CAPTCHA_ERROR);
        }
        // 判断用户是否存在
        User loginUser = new LambdaQueryChainWrapper<>(userMapper)
                .select(User::getId, User::getUserAccount, User::getPassword,
                        User::getUserName, User::getUserRole,
                        User::getAvatar, User::getStatus)
                .eq(User::getUserAccount, userLoginDTO.getUserAccount())
                .one();
        if (loginUser == null) {
            throw new AccountNotFoundException(ResultEnum.USER_NOT_EXIST);
        }
        log.info("loginUser: {}", loginUser);
        // 判断密码是否正确
        String md5Password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        if (!md5Password.equals(loginUser.getPassword())) {
            throw new PasswordErrorException(ResultEnum.USER_PASSWORD_ERROR);
        }
        // 判断用户状态是否正常
        if (!loginUser.getStatus().equals(1)) {
            throw new AccountForbiddenException(ResultEnum.USER_ACCOUNT_FORBIDDEN);
        }
        // 生成token
        String token = JwtUtils.generateToken(Map.of("userId", loginUser.getId(),
                        "userRole",loginUser.getUserRole()),
                "user");
        //构建响应对象
        UserLoginVO vo = UserLoginVO.builder()
                .userName(loginUser.getUserName())
                .avatar(loginUser.getAvatar())
                .token(token)
                .build();

        return Result.success(vo);
    }
}




